﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using SweetSurvey.Models;
using SweetSurvey.Models.Repositories;
using SweetSurvey.Models.ViewModels;

namespace SweetSurvey.Controllers
{
    public class AnswerController : ControllerBase
    {
        #region Fields

        private IParticipatorRepository participatorRepository;
        private IAnswerRepository answerRepository;
        private IOptionRepository optionRepository;

        #endregion

        #region Constructors

        public AnswerController(
            IParticipatorRepository participatorRepository,
            IAnswerRepository answerRepository,
            IOptionRepository optionRepository)
        {
            this.participatorRepository = participatorRepository;
            this.answerRepository = answerRepository;
            this.optionRepository = optionRepository;
        }

        #endregion

        //
        // POST: /Answer/SubmitAnswers

        public ActionResult SubmitAnswers(string surveyId, string answersString)
        {
            // desrialize
            var serializer = new JavaScriptSerializer();
            var answers = serializer.Deserialize<List<AnswerViewModel>>(answersString);

            // get participator id
            string participatorId = this.participatorRepository.Create(new Participator() { Date = DateTime.Now });

            // store to database
            foreach (var answer in answers)
            {
                Answer model = new Answer();
                answer.OptionRepository = this.optionRepository;
                answer.Apply(ref model);
                model.ParticipatorId = participatorId;
                this.answerRepository.Create(model);
            }
            // end
            return Json(null);
        }
    }
}
